"""
XtQuant Client Mode Initialization

This module MUST be imported BEFORE any xtquant modules to properly
configure client mode and prevent automatic remote server connections.

Usage:
    # At the very beginning of your main.py or gateway imports
    from vnpy_xt.xt_client_mode import setup_client_mode
    setup_client_mode()  # Call this BEFORE importing xtdata
"""

import os
import sys


def setup_client_mode() -> None:
    """
    Setup client mode to prevent xtdata from connecting to remote servers.
    
    This function MUST be called BEFORE importing xtquant modules.
    """
    # Check if we should use client mode
    try:
        from vnpy.trader.setting import SETTINGS
        username = SETTINGS.get("datafeed.username", "")
    except:
        # If SETTINGS not available, check environment variable
        username = os.environ.get("XT_USERNAME", "")
    
    if username == "client":
        print("🔧 [xt_client_mode] Configuring Client Mode...")
        
        # Set environment variables to force local mode
        os.environ['XT_LOCAL_MODE'] = '1'
        os.environ['XT_DISABLE_REMOTE'] = '1'
        
        # Now we can safely import xtdatacenter
        try:
            from xtquant import xtdatacenter as xtdc
            
            # Clear remote server list IMMEDIATELY
            xtdc.set_allow_optmize_address([])
            print("✅ [xt_client_mode] Remote servers disabled")
            
        except Exception as e:
            print(f"⚠️  [xt_client_mode] Warning: {e}")
        
        print("✅ [xt_client_mode] Client mode configured successfully")


def force_client_mode() -> None:
    """
    Force client mode even if already imported.
    
    Use this as a last resort if xtdata was already imported.
    """
    try:
        from xtquant import xtdatacenter as xtdc
        xtdc.set_allow_optmize_address([])
        print("✅ [xt_client_mode] Forced remote servers to be disabled")
    except Exception as e:
        print(f"❌ [xt_client_mode] Failed to force client mode: {e}")


# Auto-setup if this module is imported
if __name__ != "__main__":
    # Check if we should auto-setup
    try:
        from vnpy.trader.setting import SETTINGS
        if SETTINGS.get("datafeed.username", "") == "client":
            setup_client_mode()
    except:
        pass
